package arrayOps

import (
	"fmt"
	C "gitee.com/ljfirst/algo-go-sdk/common/constant"
)

/**
 * @author ljfirst
 * @version V1.0
 * @date 2023/7/15 17:21
 * @author-Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description
 **/
type DiffArray struct {
	diffArray []int
}

func (m *DiffArray) BuildDiffArray(array []int) {
	if len(array) == 0 {
		return
	}
	m.diffArray = make([]int, len(array), len(array))
	m.diffArray[0] = array[0]
	for i := 1; i < len(array); i++ {
		m.diffArray[i] = array[i] - array[i-1]
	}
}

// 对闭区间 [i,j] 增加 val
func (m *DiffArray) Increase(i, j, val int) {
	if i < 0 || j < 0 {
		fmt.Println("DiffArray error :i, j out of index")
		return
	}
	if i < len(m.diffArray) {
		m.diffArray[i] += val
	}
	if j+1 < len(m.diffArray) {
		m.diffArray[j+1] -= val
	}
}

func (m *DiffArray) GetDiffArray() []int {
	if len(m.diffArray) == 0 {
		return nil
	}
	array := make([]int, len(m.diffArray), len(m.diffArray))
	array[0] = m.diffArray[0]
	// attention : index 从 1 开始
	for i := 1; i < len(m.diffArray); i++ {
		array[i] = array[i-1] + m.diffArray[i]
	}
	return array
}

func (m *DiffArray) GetAttribute() *C.Attribute {
	return &C.Attribute{
		Tags: []string{C.DiffArray},
		Desc: &C.Desc{
			Name:   "DiffArray",
			NameCn: "差分数组",
			ParamsDesc: map[string]string{
			},
			Example: map[int]string{
			},
		},
	}
}
